package org.example;

import org.apache.hadoop.hbase.util.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

public class SplitUtil {
  private static final Logger LOG = LoggerFactory.getLogger(SplitUtil.class);

  public static byte[][] getSplitKeys(int splitNum) {
    byte[][] splitKeys = new byte[splitNum-1][];

    int len = String.valueOf(splitNum).length();
    for(int i=1; i<splitNum; i++) {
      System.out.println(fillWithZero(String.valueOf(i),2));
      splitKeys[i-1] = Bytes.toBytes(fillWithZero(String.valueOf(i),2));
    }
    return splitKeys;
  }

  public static String fillWithZero(String s, int len) {
    int strLen = s.length();
    if (strLen>=len) {
      return s.substring(0,len);
    } else {
      StringBuilder buffer = new StringBuilder();
      for (int i = 0; i < (len-strLen); i++) {
        buffer.append(0);
      }
      buffer.append(s);
      return buffer.toString();
    }
  }

  public static String getRowKey(String rowKey, int splitNum) {
    int rang = Math.abs(rowKey.hashCode()%splitNum);
    return fillWithZero(String.valueOf(rang),2) + "_" + rowKey;
  }

  public static String getOriKey(String rowKey) {
    if (rowKey.length()<3) {
      LOG.error("Error length, row key: " + rowKey);
    }
    if ((rowKey.length()>=3)&&(rowKey.charAt(2)=='_')) {
      return rowKey.substring(3);
    }
    else {
      return rowKey.substring(2);
    }
  }

  public static void main(String[] args) throws InterruptedException {
    System.out.println(Arrays.deepToString(getSplitKeys(5)));
    System.out.println(getOriKey("01_kawefwef"));
    long start = System.currentTimeMillis();
    Thread.sleep(2000);
    long end = System.currentTimeMillis();
    System.out.println((end-start)/1000);
  }
}
